from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.service import Service
import time
import mysql.connector

# 设置ChromeDriver服务
options = webdriver.EdgeOptions()

# 创建WebDriver实例并加载页面
driver = webdriver.Edge( options=options)
driver.get('https://search.jd.com/Search?keyword=%E7%94%9F%E9%B2%9C%E7%BE%8E%E9%A3%9F')

# 数据库连接
db = mysql.connector.connect(user='test', password='123456abc',
                            host='localhost',
                            database='mall')
cursor = db.cursor()

# 获取查询结果
cursor.execute("SELECT * FROM pms_product_category WHERE ISNULL(icon)")
results = cursor.fetchall()
db.commit()     # 提交事务

COUNT=0;

# 循环遍历关键词列表
for item in results:
    try:
        # 定位搜索框
        search_box = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.XPATH, '//input[@id="key"]'))
        )
        
        # 清除搜索框并输入关键词
        search_box.clear()
        search_box.send_keys(item[2])

        # submit = WebDriverWait(driver, 10).until(
        #     EC.presence_of_element_located((By.XPATH, "//button[contains(@onclick, \"search('key');return false;\")]"))
        # )

        # 定位搜索按钮
        submit = WebDriverWait(driver, 10).until(
           EC.presence_of_element_located((By.XPATH, "//button[contains(@onclick, \"search('key');return false;\")]"))
        )
        # submit = WebDriverWait(driver, 10).until(
        #    EC.element_to_be_clickable((By.XPATH, "//button[contains(@onclick, 'search('key');return false;')]"))
        #    EC.element_to_be_clickable((By.XPATH, '//button[contains(@onclick, "搜索")]'))
        #    EC.element_to_be_clickable((By.CLASS_NAME, "button cw-icon"))
        # )
        # submit=driver.find_element(By.XPATH, '//button[@class="button cw-icon" and text()="搜索"]')
        # submit = driver.find_element(By.XPATH, "//button[contains(text(), '搜索')]")
        # 点击搜索按钮
        submit.click()
        # time.sleep(3)
        # driver.find_element_by_xpath('//button[@clstag="h|keycount|head|search_a"]/i').click()

        if  COUNT==0:
            COUNT=1
            print("######################COUNT==000000#################################")
            time.sleep(20)
        else:
            time.sleep(4)
            print("######################COUNT==11111#################################")

        # 获取第一个商品的图片元素
        # first_item_image = WebDriverWait(driver, 10).until(
        #    EC.presence_of_element_located(By.CSS_SELECTOR, "img[data-img='1'][data-lazy-img='done']")
        # )
        locator = (By.CSS_SELECTOR, "img[data-img='1'][data-lazy-img='done']")
        first_item_image = driver.find_elements(*locator)
        # first_item_image = driver.find_elements(By.CSS_SELECTOR, '.MainPic--mainPicWrapper--iv9Yv90 img')  # CSS选择器可能需要根据实际网页结构调整
        if first_item_image:
            image_url = first_item_image[0].get_attribute('src')
            print("######################333333333333333333#################################" + image_url)
            # 更新数据库中的图标链接
            update_query = "UPDATE pms_product_category SET icon = %s WHERE id = %s"
            cursor.execute(update_query, (image_url, item[0]))
            db.commit()
        else:
            print("No images found.")
    
    except Exception as e:
        print(f"An error occurred: {e}")

# 关闭浏览器
driver.quit()